package com.ruoyi.web.service.impl;

import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.domain.Comment;
import com.ruoyi.web.domain.Image;
import com.ruoyi.web.domain.Post;
import com.ruoyi.web.mapper.PostMapper;
import com.ruoyi.web.mapper.UserFriendMapper;
import com.ruoyi.web.service.FileService;
import com.ruoyi.web.service.IImageService;
import com.ruoyi.web.service.IPostService;
import com.ruoyi.web.service.IUserFriendService;
import com.ruoyi.web.utils.UserMsgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 * postService业务层处理
 *
 * @author ruoyi
 * @date 2024-04-22
 */
@Service
public class PostServiceImpl implements IPostService {
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private FileService fileService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IImageService imageService;
    @Autowired
    private UserFriendMapper userFriendMapper;


    /**
     * 查询post
     *
     * @param id post主键
     * @return post
     */
    @Override
    public Post selectPostById(Long id) {
        // 查询post主体
        Post post = postMapper.selectPostById(id);
        // 楼主的头像url
        if (!StringUtils.isEmpty(post.getAvatar())) {
            // 头像非空，获取url
            post.setAvatar(UserMsgUtil.subAvatar(post.getAvatar()));
        }
        // 帖子的图片
        Image image = new Image();
        image.setPostId(post.getId());
        List<Image> images = imageService.selectImageList(image);
        // 公有读oss的方案
        String prefix = "https://kangningcom.oss-cn-shanghai.aliyuncs.com/";
        if (!images.isEmpty()) {
            images = images.stream().peek(item -> {
                // 公有读oss的方案
                item.setImage(prefix + item.getImage());
                /*// 私有读oss的方案
                String url = fileService.getUrl(item.getImage()).toString();
                item.setImage(url);*/
            }).collect(Collectors.toList());
            post.setImages(images);
        }
        // 评论的头像url
        List<Comment> commentList = post.getCommentList();
        commentList = commentList.stream().peek(item -> {
            if (!StringUtils.isEmpty(item.getAvatar())) {
                // 头像非空，获取url
                item.setAvatar(UserMsgUtil.subAvatar(item.getAvatar()));
            }
        }).collect(Collectors.toList());
        // 再赋值回去
        post.setCommentList(commentList);

        // 判断当前用户与楼主是否为好友
        Long userId = post.getUserId();// 楼主id
        if (UserMsgUtil.getUserId() != null) {
            // 当前用户的userId
            // 判断两者是不是好友
            Boolean friendFlag = judgeFriends(UserMsgUtil.getUserId(), userId);
            post.setFriendFlag(friendFlag);
        }

        return post;
    }

    /**
     * 判断两人是不是好友(true是好友、false不是好友)
     *
     * @return
     */
    public Boolean judgeFriends(Long userId, Long friendId) {
        // 若进入的是自己的帖子，也返回true
        if (userId == friendId) {
            return true;
        }
        List<SysUser> friends = userFriendMapper.selectFriendsByUserId(userId);
        if (!friends.isEmpty()) {
            for (SysUser friend : friends) {
                if (friend.getUserId() == friendId) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 查询post列表
     *
     * @param post post
     * @return post
     */
    @Override
    public List<Post> selectPostListOri(Post post) {
        //查询所有
        List<Post> postList = postMapper.selectPostList(post);
        return postList;
    }

    /**
     * 查询post列表(并且为帖子自带的头像赋值)
     *
     * @param post post
     * @return post
     */
    @Override
    public List<Post> selectPostList(Post post, Boolean myFlag) {
        if (myFlag) {
            // 只查询自己的
            // 获取userId并作为条件赋值
            if (getUserId() != null) {
                post.setUserId(getUserId());
            }
        }

        //查询所有
        List<Post> postList = postMapper.selectPostList(post);
        postList = postList.stream().peek(item -> {
            item.setAvatar(UserMsgUtil.subAvatar(item.getAvatar()));
        }).collect(Collectors.toList());
        return postList;
    }

    /**
     * 获取当前登录用户的userId
     */
    private Long getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken)) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                LoginUser loginUser = (LoginUser) principal;
                // 获取userId
                Long userId = loginUser.getUserId();
                return userId;
            }
        }
        return null;
    }

    /**
     * 新增post
     *
     * @param post post
     * @return 结果
     */
    @Override
    public int insertPost(Post post) {
        // 获取userId并赋值
        if (getUserId() == null) {
            // 每一个贴子都应该有useId
            return 0;
        }
        // 为userId、userName和avatar赋值(此处简单使用了username,后面要改成nickName)
        post.setUserId(getUserId());
        SysUser sysUser = userService.selectUserById(getUserId());
        post.setUsername(sysUser.getUserName());
        if (!StringUtils.isEmpty(sysUser.getAvatar())) {
            post.setAvatar(sysUser.getAvatar());
        }

        return postMapper.insertPost(post);
    }

    /**
     * 修改post
     *
     * @param post post
     * @return 结果
     */
    @Override
    public int updatePost(Post post) {
        return postMapper.updatePost(post);
    }

    /**
     * 批量删除post
     *
     * @param ids 需要删除的post主键
     * @return 结果
     */
    @Override
    public int deletePostByIds(Long[] ids) {
        return postMapper.deletePostByIds(ids);
    }

    /**
     * 删除post信息
     *
     * @param id post主键
     * @return 结果
     */
    @Override
    public int deletePostById(Long id) {
        return postMapper.deletePostById(id);
    }
}
